package com.seu.githubcn.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seu.githubcn.config.Result;
import com.seu.githubcn.entity.User;
import com.seu.githubcn.mapper.UserMapper;
import com.seu.githubcn.utils.Sha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import static com.seu.githubcn.utils.Utils.getRandomString;

@RestController
@RequestMapping()
public class UserController {
    @Autowired
    UserMapper userMapper;

    @PostMapping("/user/login")
    public Result<?> login(@RequestBody User user) {
        if(user==null){
            return new Result<>(405, null, "接收失败");
        }

        User query = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, user.getUserName())
        );


        //查询不到用户返回错误
        if (query == null) {
            return new Result<>(401, null, "用户名或密码错误！");
        }

        if (!Sha.getSHA1(user.getUserPassword() + query.getSalt(), false).
                equals(query.getUserPassword())) {
            return new Result<>(401, null, "用户名或密码错误！");
        }
        Map<Object, Object> resInfo = new HashMap<>();
        resInfo.put("userId",query.getUserId());
        resInfo.put("userName", query.getUserName());
        resInfo.put("userPermission", query.getUserPermission().toString());
        return new Result<>(200, resInfo, "登录成功！");
    }

    @GetMapping ("/user/info")
    public Result<Object> info(@RequestParam(defaultValue = "0") String userIds
    ){
        Integer userId=Integer.parseInt(userIds);
        User user=
                userMapper.selectById(userId);
        return new Result<>(200,user,"个人信息读取成功！");
    }


    @PostMapping("user/register")
    public Result<?> regis(@RequestBody User user) {
        User query = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, user.getUserName())
        );
        if (query != null) {
            return new Result<>(401, null, "用户名重复！");
        }
        User newOne = new User();
        newOne.setUserName(user.getUserName());
        newOne.setSalt(getRandomString(5));
        newOne.setUserPassword(Sha.getSHA1(user.getUserPassword() + newOne.getSalt(), false));
        newOne.setUserPermission(User.Permission.AVERAGE);
        newOne.setDescription("该用户太懒了，还没有自己的个人介绍@_@");
        userMapper.insert(newOne);
        return new Result<>(200, null, "注册成功！");

    }


    @PostMapping("user/renew/name")
    public Result<?> renewName(@RequestBody User user){
        User query =
                userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, user.getUserName())
        );
        if (query != null) {
            return new Result<>(401, null, "用户名重复！");
        }
        User recent =
                userMapper.selectById(user.getUserId());
        recent.setUserName(user.getUserName());
        userMapper.updateById(recent);
        return new Result<>(200,null,"修改成功");
    }

    @PostMapping("user/renew/password")
    public Result<?> renewPassword(@RequestBody User user){
        User recent =
                userMapper.selectById(user.getUserId());
        recent.setSalt(getRandomString(5));
        recent.setUserPassword(Sha.getSHA1(user.getUserPassword() + recent.getSalt(), false));
        userMapper.updateById(recent);
        return new Result<>(200,null,"修改成功");
    }

    @PostMapping("/user/renew/des")
    public Result<?> renewDescription(@RequestBody User user){
        User recent =
                userMapper.selectById(user.getUserId());
        recent.setDescription(user.getDescription());
        userMapper.updateById(recent);
        return new Result<>(200,null,"修改成功");
    }

    private static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();

    }

    /**
     * 全局的搜索用户
     * @param currentPage 当前页
     * @param pageSize 页条数
     * @param search 搜索关键字
     * @return 200
     */
    @GetMapping("/user/search")
    public Result<?> publicSearch(@RequestParam(defaultValue = "1") Integer currentPage,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(defaultValue = "") String search){

        Page<User> searchPage =
                userMapper.selectPage(new Page<>(currentPage,pageSize),
                        Wrappers.<User>lambdaQuery()
                                        .like(User::getUserName,search)
                                        .or()
                                        .like(User::getDescription,search));


        return new Result<>(200,searchPage,"查询成功!");
    }

    @GetMapping("/user/list")
    public Result<?> userList(@RequestParam(defaultValue = "") String search){
        var userList =
                userMapper.selectList(Wrappers.<User>lambdaQuery()
                        .like(User::getUserName,search));
        return new Result<>(200,userList,"查询成功!");
    }

    @GetMapping("/user/id")
    public Result<?> userId(@RequestParam(defaultValue = "0") String userName){
        User user =
                userMapper.selectOne(Wrappers.<User>lambdaQuery()
                        .eq(User::getUserName, userName));
        return new Result<>(200,user.getUserId().toString(),"查询成功!");
    }
}
